<?php
/*
 * Copyright (c) Taras Kudla, 2010
 */
class mod_useradmin extends module
	{
	function init(){
	
	}
	/* Functions to process under Groups   */
	public function GetGroupsList()
		{

		}

	public function GetGroup()
		{
	

		
		}
		
	public function AddGroup()
		{
					
		}

       public function DeleteGroup(){
           
            if(!isset($_GET["d"]) || !is_numeric($_GET["d"])){

                return $this->api->error($this->lang->get("group1") );

            } else $id=$this->api->escapeString($_GET["d"]);

            $Query=$this->api->dbo->select("groups","name","where id='".$id."' limit 1 offset 0",_RESULT_ROW);

            if(count($Query)!=1){
                return $this->api->error($this->lang->get("group1") );
            }

            if($this->api->checkPOST("Submit")){

                $this->api->dbo->delete("users","where groupid='".$id."'");

                $this->api->dbo->delete("groups","where id='".$id."'");

                $this->api->log->Write("Group '".$Query["name"]."' with id $id was removed");

                return $this->api->message($this->lang->get("group2"));
            }

            $Users=$this->api->dbo->select("users","COUNT(*) as count","where groupid='".$id."' ",_RESULT_ROW);

            $Users=$Users["count"];

            return $this->api->view->GetTemplate("deletegroup",array("name"=>$Query["name"],"users"=>$Users) );
        }


	# updating group information
	public function updategroup(){
		# checking parameters
		if( !isset($_GET["group"]) || !is_numeric($_GET["group"]) ){
			return $this->api->message("Error in input parameters");
		} else $group = (int)$_GET["group"];
		if( $group <= 2 ){
			return $this->api->message($this->lang->get("group8"));
		}
		# checking if dataentered
		if( $this->api->checkPOST("name","Submit") ){
			$oldname = $this->api->dbo->select("groups","name","where id='$group'",_RESULT_ONE);
			$name = $this->api->escapeString($_POST["name"]);
			if( $oldname!=$name){
			$this->api->dbo->update("groups"," set name='$name' where id='$group'");
			}
		}
		$name = $this->api->dbo->select("groups","name","where id='$group' limit 1 offset 0",_RESULT_ONE);
		return $this->api->view->template("updategroup",array("name"=>$name));	
	}	
	
	/* Functions to process under users */	

        public function AddNewUser(){

        }

	public function GetUsers()
		{
			
		$total=$this->api->dbo->select("users","COUNT(*) as count"," ",_RESULT_ONE);
		
		$str=null;
		
		$usersPerPage=20;		
		
		/*
		 * Checking for limit and pages properties
		 */
		
                $pages=(int)round($total/$usersPerPage+0.459);

                $page=( isset($_GET["page"])
        
					&& is_numeric($_GET["page"])
					
					&& $_GET["page"]<=$pages
					
					&& $_GET["page"]>0
					
				)?$_GET["page"]:0;

		$sqlLimit="limit ".$usersPerPage." offset ".($page*$usersPerPage);
				
		/*
		 * Checking for order properties
		 */	
		$order=(isset($_GET["order"])?$this->api->toSafe($_GET["order"],1):"id");		
		
		$desc=isset($_GET["orderDesc"])?null:"desc";
		
		$sqlOrder="order by ".$order." ".$desc;
		
		/*
		 * Cheching for filter properties
		 */		

		$useFilter=isset($_GET["filter"])?true:false;
		
		$filterParams=null;
		
		$filterForm=null;		
		
		if($useFilter){
			
			$filter["filterName"]=isset($_GET["filterName"])?" firstname like '%".$this->api->escapeString($_GET["filterName"])."%' ":null;
			
			$filter["filterSubname"]=isset($_GET["filterSubname"])?" lastname like '%".$this->api->escapeString($_GET["filterSubname"])."%' ":null;
		
			$filter["filterEmail"]=isset($_GET["filterEmail"])?" email like '%".$this->api->escapeString($_GET["filterEmail"])."%' ":null;
			
			$filter["filterGroup"]=(isset($_GET["filterGroup"]) && is_numeric($_GET["filterGroup"]) ) ?" groupid='".$this->api->escapeString($_GET["filterGroup"])."' ":null;
			
			$i=0;
			
			$sqlWhere=" where ";
			
			$filterParams="&filter";
			
			foreach($filter as $k=>$v){

				if($v==null)continue;
				
				$sqlWhere.=(($i!=0)?" and ":null).$v;
				
				$filterParams.="&".$k."=".$_GET[$k];
				
				$i++;				
			}
			
			if($i==0){
				
				$sqlWhere=null;
				
				$filterParams=null;
				
			}
			
			$sqlQuery=$sqlWhere.$sqlOrder." ".$sqlLimit;
		
					
			
		}
		else {
			
			$sqlQuery=$sqlOrder." ".$sqlLimit;
			
		}
		
		$filterFormUrl=$this->api->base->GetActionLink("useradmin-getusers","page=".$page."&order=firstname".(isset($_GET["orderDesc"])?null:"&orderDesc"));
		
		
		
		
		$Groups = $this->api->dbo->select("groups","id,name");
		
		$filterForm = $this->api->view->template("filterform",array(
					"filterName"=>isset($_GET["filterName"])?$_GET["filterName"]:null,
					"filterSubname"=>isset($_GET["Subname"])?$_GET["filterSubname"]:null,
					"filterEmail"=>isset($_GET["filterEmail"])?$_GET["filterEmail"]:null,
					"filterGroup"=>isset($_GET["filterGroup"])?$_GET["filterGroup"]:null,
					"Groups"=>&$Groups,
					"filterFormUrl"=>$filterFormUrl
					));
		/*
		 * Forming title links
		 */
				
		
		$params="page=".$page."&order=firstname".(isset($_GET["orderDesc"])?null:"&orderDesc").$filterParams;
		
		$firstNameLink=$this->api->base->BuildActionLink("useradmin-GetUsers",$params,$this->lang->get("u4")." ".((isset($_GET["orderDesc"]) && $order=="firstname" )?"▲":"▼"));

		
		$params="page=".$page."order=lastname".(isset($_GET["orderDesc"])?null:"&orderDesc").$filterParams;
		
		$lastNameLink=$this->api->base->BuildActionLink("useradmin-GetUsers",$params,$this->lang->get("u5")." ".((isset($_GET["orderDesc"]) && $order=="lastname")?"▲":"▼"));
		
		
		$params="page=".$page."order=email".(isset($_GET["orderDesc"])?null:"&orderDesc").$filterParams;
		
		$emailLink=$this->api->base->BuildActionLink("useradmin-GetUsers",$params,$this->lang->get("u6")." ".((isset($_GET["orderDesc"]) && $order=="email" )?"▲":"▼"));
		

		$params="page=".$page."order=groupid".(isset($_GET["orderDesc"])?null:"&orderDesc").$filterParams;
		
		$groupOrderLink=$this->api->base->BuildActionLink("useradmin-GetUsers",$params,$this->lang->get("u9")." ".((isset($_GET["orderDesc"]) && $order=="groupid" )?"▲":"▼"));		
		
		
		$params="page=".$page."order=lastdate".(isset($_GET["orderDesc"])?null:"&orderDesc").$filterParams;
		
		$lastEnterLink=$this->api->base->BuildActionLink("useradmin-GetUsers",$params,$this->lang->get("u10")." ".((isset($_GET["orderDesc"]) && $order=="lastdate" )?"▲":"▼"));
		
		
		/*
		 * 
		 */
		$_=$this->api->dbo->select("users","id,nickname,firstname,lastname,email,lastip,groupid,lastdate",$sqlQuery);
		
		/*
		 * Pages tool
		 */
		$pagesForm=$this->api->tools->Pages($pages,$page,"useradmin-GetUsers","order=".$order.(isset($_GET["orderDesc"])?null:"&orderDesc").$filterParams,"page","page","spage");
		
		
		/*
		 * 
		 */
		return $this->api->view->GetTemplate("userlist",array("num"=>count($_),
		
		"filterForm"=>$filterForm,
		
		"f1"=>$firstNameLink,
		
		"f2"=>$lastNameLink,
		
		"f4"=>$groupOrderLink,
		
		"f3"=>$emailLink,
			
		"f5"=>$lastEnterLink,
		
		"order"=>$order,
		
		"pages"=>$pagesForm,
		
		"groups"=>&$groupsList,
		
		"q"=>&$_
		
		));


		}
	
	private function GroupSelect($id=null){

		$q=$this->api->dbo->select("groups","id,name"," order by id limit 200 offset 0");
		
		$t=null;
		
		$i=0;
		
		while($i<count($q)){
			
			$t.="<option  value='".$q[$i]["id"]."'  ".($id==$q[$i]["id"]?"selected":"")."  >".$q[$i]["name"]."</option>";
			
			$i++;
		}
		
		return $t;
	}
		
		
	
	public function GetUser()
		{
		
				
		if(!isset($_GET["user"]))
			{
			
			return false;
			}  
		
		
		$id=$this->api->escapeString($_GET["user"]);
		
		
		
		$_=	$this->api->dbo->select("users,groups","
		users.id,users.nickname,users.firstname,users.lastname,users.lastdate,users.lastip,users.personal,users.image,users.email,users.groupid,groups.name"," 
		where users.id='".$id."' and groups.id=users.groupid limit 1 offset 0");
		
		if(count ($_)!=1)
			{
			
			return $this->api->errors->Error("No User Found");
			}		
		$image=$this->api->file->GetFoto($_[0]["image"]);
		
		$this->api->base->Way[]=array("v"=>$this->lang->get("w1"),"a"=>"useradmin-getusers");	
		
		$this->api->base->Way[]=array("v"=>$this->lang->get("u8").":".$_[0]["firstname"]." ".$_[0]["lastname"]);	

		return $this->api->view->GetTemplate("useradmin","edituser",array("user"=>&$_,"image"=>$image));
			
		}
	
	public function DeleteUser($_=null)
		{
		
		$id= ( $_!=null && is_numeric($_) )?$_:((isset($_GET["d"]) && is_numeric($_GET["d"]))?$_GET["d"]:null);
		
			
		if($id==null || !is_numeric($id) )
			{
			
			return $this->api->errors->Error("Error in argcv[]");
			}
				
			
		$u=$this->api->dbo->select("users","image,id","where id='".$id."' limit 1");		
				
		if( count($u) !=1 )
			{
			
			return $this->api->errors->Error("No user found");
			}
		
					
		$f["title"]  ="Delete this user ?";
		
		$f["options"]=array("action"=>$this->A("DeleteUser"),"method"=>"post","id"=>"deleteGroup" );
		
		$f["input"][0]  =array("title"=>"","name"=>"todelete","type"=>"hidden","value"=>$u[0]["id"]);
		
		$f["input"][1]  =array("type"=>"Button","name"=>"Submit","value"=>"YES");
			
					
		if($this->api->checkPOST("todelete","Submit"))
				{
				$id=$this->api->toSafe($_POST["todelete"],1);
				
				if ( (int)$u[0]["image"] != 0 )
					{
					$this->api->file->delete($u[0]["image"]);
										
					}				
				
				$this->api->dbo->delete("users"," where id='".$id."'");
				
				$this->api->log->write("user $id deleted");
												
				
				return $this->api->errors->Message("Delete Successfull"); 
							
				}
		
		
		return $this->api->base->FormGenerator($f);
		}		
	


	
	}
?>
